3 Sum [Two Pointers]¶
Time: O(N^2); Space: O(1); medium
Given an array nums of N integers, are there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Notes:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c)
The solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, 0, 1], [-1, -1, 2]]
Hints:
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand!
For the two-sum problem, if we fix one of the numbers, say ‘x’, we have to scan the entire array to find the next number ‘y’ which is value - x, where value is the input parameter. Can we change our array somehow so that this search becomes faster?
The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
[17]:
class Solution1(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums, result, i = sorted(nums), [], 0
while i < len(nums) - 2:
if i == 0 or nums[i] != nums[i - 1]:
j, k = i + 1, len(nums) - 1
while j < k:
if nums[i] + nums[j] + nums[k] < 0:
j += 1
elif nums[i] + nums[j] + nums[k] > 0:
k -= 1
else:
result.append([nums[i], nums[j], nums[k]])
j, k = j + 1, k - 1
while j < k and nums[j] == nums[j - 1]:
j += 1
while j < k and nums[k] == nums[k + 1]:
k -= 1
i += 1
return result
[18]:
s = Solution1()
nums = [-1, 0, 1, 2, -1, -4]
assert s.threeSum(nums) == [[-1, -1, 2], [-1, 0, 1]] or [[-1, 0, 1], [-1, -1, 2]]
[19]:
import collections
class Solution2(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
d = collections.Counter(nums)
nums_2 = [x[0] for x in d.items() if x[1] > 1]
nums_new = sorted([x[0] for x in d.items()])
rtn = [[0, 0, 0]] if d[0] >= 3 else []
for i, j in enumerate(nums_new):
if j <= 0:
numss2 = nums_new[i + 1:]
for x, y in enumerate(numss2):
if 0 - j - y in [j, y] and 0 - j - y in nums_2:
if sorted([j, y, 0 - j - y]) not in rtn:
rtn.append(sorted([j, y, 0 - j - y]))
if 0 - j - y not in [j, y] and 0 - j - y in nums_new:
if sorted([j, y, 0 - j - y]) not in rtn:
rtn.append(sorted([j, y, 0 - j - y]))
return rtn
[20]:
s = Solution2()
nums = [-1, 0, 1, 2, -1, -4]
assert s.threeSum(nums) == [[-1, -1, 2], [-1, 0, 1]] or [[-1, 0, 1], [-1, -1, 2]]